package com.ccb.sc.login.service.impl;

import com.ccb.sc.auth.Token;
import com.ccb.sc.login.service.IAppTokenService;
import com.ccb.sc.common.modules.common.service.IRedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

/**
 * @author ken
 * @version 1.0
 * @date 2020-09-15
 */
@Slf4j
@Service
public class AppAppTokenServiceImpl implements IAppTokenService {

    private IRedisService redisService;

    /**
     * token过期时间
     */
    @Value("${app.token.expiry:7}")
    private int days;

    @Override
    public void storeToken(String key, Token token) {
        this.redisService.set(key, token, days, TimeUnit.DAYS);
    }

    @Override
    public Token getTokenModel(String key) {
        return (Token) this.redisService.get(key);
        /*try {
            Token token = new Token();
            Object object = this.redisService.get(key);
            if (object != null) {
                log.info("redis token object:[{}]", object);
                token = JSON.parseObject(JSON.toJSONString(object.toString()), Token.class);
            }
            return token;
        } catch (SerializationException | JSONException ex) {
            log.error("token json parse error", ex);
            return null;
        }*/
    }

    @Override
    public Token getTokenModel(String key, String sign) {
        Token token = getTokenModel(key);
        if (token == null) {
            return null;
        }
        if (StringUtils.hasText(sign)) {
            return sign.equalsIgnoreCase(token.getSign()) ? token : null;
        }
        return token;
    }

    @Override
    public void delayToken(String key) {
        this.redisService.expire(key, days, TimeUnit.DAYS);
    }

    @Override
    public void deleteToken(String key) {
        this.redisService.delete(key);
    }

    @Autowired
    public void setRedisService(IRedisService redisService) {
        this.redisService = redisService;
    }
}
